package imsdk

import (
	"encoding/json"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/http"
	"math/rand"
)

/*
	{
	    "SyncOtherMachine": 2, // 消息不同步至发送方
	    "To_Account": [ // 目标帐号列表
	        "bonnie",
	        "rong"
	    ],
	    "MsgSeq": 28360, // 消息序列号
	    "MsgRandom": 19901224, // 消息随机数
	    "MsgBody": [ // 消息
	        {
	            "MsgType": "TIMTextElem", // 消息类型，TIMTextElem为文本消息
	            "MsgContent": {
	                "Text": "hi, beauty" // 消息文本
	            }
	        }
	    ],
	    "CloudCustomData": "your cloud custom data"
	}
*/
type (
	BatchSendUserMsg struct {
		SyncOtherMachine int8      `json:"SyncOtherMachine,omitempty"` // 消息不同步至发送方
		ToAccount        []string  `json:"To_Account"`                 // 必填
		MsgLifeTime      int       `json:"MsgLifeTime"`                // 消息离线保存时长（单位：秒），最长为7天（604800秒）
		MsgRandom        int32     `json:"MsgRandom"`
		MsgBodies        []MsgBody `json:"MsgBody"`
	}
)

// BatchSendUser 批量單發消息
func (s sdk) BatchSendUser(userIds []string, msg string) {
	random := rand.Int31()
	url := s.BuildRestfulUrl("/openim/batchsendmsg")

	var msgBodies []MsgBody
	msgBodies = append(msgBodies, MsgBody{
		MsgType:    "TIMCustomElem",
		MsgContent: MsgContent{Data: msg},
	})

	j, err := json.Marshal(BatchSendUserMsg{
		SyncOtherMachine: 2, // 消息不同步至发送方
		MsgRandom:        random,
		ToAccount:        userIds,
		MsgBodies:        msgBodies,
	})
	if err != nil {
		return
	}

	r, err := http.HttpPost(url, string(j), connTimeoutMs, serveTimeoutMs, "application/json")
	if err != nil {
		global.Log.Errorf("GroupSendUser error: %v, result: %s", err, r)
		return
	}
	global.Log.Debugf("GroupSendUser: %s.  http result: %s", string(j), string(r))

}
